package com.song.codesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.song.codesandbox.model.*;
import com.song.codesandbox.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StopWatch;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
public abstract class JavaCodeSandBoxTemplate implements CodeSandBox {

    /**
     * 全局代码存放目录
     */
    private static final String GLOBAL_CODE_DIR_NAME = "TmpCode";

    /**
     * 全局代码文件名
     */
    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    /**
     * 超时时间，单位：毫秒
     */
    private static final long TIME_OUT = 5000L;

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest request) {
        List<String> inputList = request.getInputList();
        String code = request.getCode();
        String language = request.getLanguage();
        if (inputList == null || inputList.isEmpty() || StrUtil.isBlank(code) || StrUtil.isBlank(language)) {
            return createErrorResponse(new IllegalArgumentException("参数不合法"));
        }
        return executeCode(request.getInputList(), request.getCode(), request.getLanguage());
    }

    /**
     * 执行代码
     *
     * @param inputList 程序的输入
     * @param code      程序要执行的代码
     * @param language  编程语言
     * @return
     */
    @Override
    public ExecuteCodeResponse executeCode(List<String> inputList, String code, String language) {

        /**
         * 将用户代码保存为文件
         */
        File userCodeFile = saveCodeToFile(code);

        /**
         * 编译代码文件
         */
        ExecuteMessage compileExecuteMessage = compileFile(userCodeFile);
        // todo 可以进行日志输出

        /**
         * 运行代码
         */
        List<ExecuteMessage> executeMessageList = runFile(userCodeFile, inputList);

        /**
         * 整理输出结果
         */
        ExecuteCodeResponse response = formatAndOutputWithResponse(executeMessageList);
        log.info("响应结果: {}", response);

        /**
         * 删除文件
         */
        boolean is_delete = deleteFile(userCodeFile);
        if (!is_delete) {
            log.info("用户代码文件删除失败: {}", userCodeFile.getAbsolutePath());
        }
        return response;
    }

    /**
     * 将用户的代码保存为文件
     *
     * @param code 用户代码
     * @return
     */
    public File saveCodeToFile(String code) {
        // 获取用户目录
        String userDir = System.getProperty("user.dir");
        // 拼接全局的用户代码目录
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        // 判断全局代码目录是否存在，如果不存在则新建目录
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }
        // 为用户生成独立的代码存放文件夹，将用户的代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);
        return userCodeFile;
    }

    /**
     * 编译代码
     *
     * @param userCodeFile 用户代码文件
     * @return
     */
    public ExecuteMessage compileFile(File userCodeFile) {
        // todo 这里改动了一下，回头看看有什么问题: getAbsoluteFile -> getAbsolutePath
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
        log.info("编译命令: {}", compileCmd);
        ExecuteMessage compileExecuteMessage = new ExecuteMessage();
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            compileExecuteMessage = ProcessUtils.runProcess(compileProcess, ProcessExecType.COMPILE);
            if (compileExecuteMessage.getExitValue() != 0) {
                throw new RuntimeException("编译错误");
            }
            return compileExecuteMessage;
        } catch (IOException e) {
            // todo 异常自定义
            throw new RuntimeException(e);
        }
    }

    /**
     * 运行代码（文件）
     * 默认使用本机运行代码，若有需要更换其他环境运行，比如docker隔离环境，可以继承并重写此方法
     *
     * @param userCodeFile 用户的代码文件 todo 其实我们并不需要用的本身的代码或编译之后的代码，此参数是用来获取用户编译后代码的存放的父目录
     * @param inputList    代码运行需要的输入
     * @return
     */
    public List<ExecuteMessage> runFile(File userCodeFile, List<String> inputList) {
        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String arg : inputList) {
            String codeRunCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentPath, arg);
            log.info("执行命令: {}", codeRunCmd);
            try {
                Process runProcess = Runtime.getRuntime().exec(codeRunCmd);
                ProcessUtils.timeoutMonitor(runProcess, TIME_OUT);
                ExecuteMessage executeMessage = ProcessUtils.runProcess(runProcess, ProcessExecType.RUN);
                executeMessageList.add(executeMessage);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return executeMessageList;
    }

    /**
     * 整理代码输出结果，并返回响应对象
     *
     * @param executeMessageList 执行信息列表
     * @return
     */
    public ExecuteCodeResponse formatAndOutputWithResponse(List<ExecuteMessage> executeMessageList) {
        /**
         * 整理输出，构造代码执行的响应结果
         * (1) 输出结果: outputList
         * (2) 接口信息: message
         * (3) 执行状态: status
         *      1: 执行成功
         *      2: 异常
         *      3: 执行失败
         * (5) 判题信息: judgeInfo
         *    判题信息包括：程序执行信息(message)、消耗时间(time)以及消耗内存(memory)
         */
        ExecuteCodeResponse response = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        long maxTime = 0L;
        // 遍历所有执行信息
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                response.setMessage(errorMessage);
                response.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            if (executeMessage.getTime() != null) {
                maxTime = Math.max(maxTime, executeMessage.getTime());
            }
        }

        if (outputList.size() == executeMessageList.size()) {
            response.setStatus(1);
        }
        response.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        response.setJudgeInfo(judgeInfo);

        return response;
    }

    /**
     * 删除用户代码文件
     *
     * @param userCodeFile 用户代码文件
     * @return
     */
    public boolean deleteFile(File userCodeFile) {
        if (userCodeFile.getParentFile() != null) {
            String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
            boolean del = FileUtil.del(userCodeParentPath);
            log.info("用户文件删除成功: {}", userCodeParentPath);
            return del;
        }
        return true;
    }

    /**
     * 构建异常错误响应
     *
     * @param e 异常状态
     * @return 异常错误响应
     */
    private ExecuteCodeResponse createErrorResponse(Throwable e) {
        ExecuteCodeResponse response = new ExecuteCodeResponse();
        response.setOutputList(new ArrayList<>());
        response.setMessage(e.getMessage());
        response.setStatus(2);
        response.setJudgeInfo(new JudgeInfo());
        return response;
    }

}
